package com.example.anyong17_julnumgi.test;

import java.io.ObjectOutputStream.PutField;
import java.text.BreakIterator;
import java.util.ArrayList;



import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.net.rtp.RtpStream;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Chronometer;
import android.widget.TextView;
import android.widget.Toast;


public class JUL_Activity extends Activity {
	SensorManager mSm;//센서
	Chronometer mChrono;//크로메타
	TextView mCounterText;//줄넘기 카운터
	TextView mEllapse;
	
	Button mStart;//스타트,스톱 버튼
	Button mSens;//설정 버튼
	
	boolean startFlag;//스타트,스탑 플래그
	
	int sumCount=0;//총 카운터
	int mCounter = 0;//인식한 카운터
	int sufNum =0;//설정 카운터
	
	long mApplyTime ;//센서 타임
	int mSenGap= 1000;//센서 갭
	float mSenRange = 16.0f;//센서 범위
	int sSenSpeed = 800;//센서 속도
	
	long mBaseTime;//time워치 start
	long mPauseTime;//time워치 stap
	
	String lastlap;//정지된 타임 
	ArrayList<AccelValue> arValue = new ArrayList<AccelValue>();
	ArrayList<Record>arRecord = new ArrayList<Record>();
	
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.julprocess);
		
		SharedPreferences pref = getSharedPreferences("JUL", 0);//설정
		sufNum = pref.getInt("sufNum", 0);//설정
		
		
		mSm = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
		mSm.registerListener(mSensorListenr, mSm.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),SensorManager.SENSOR_DELAY_GAME);
		
		mCounterText= (TextView) findViewById(R.id.counter);
		mStart= (Button) findViewById(R.id.jul_start_btn);
		mSens = (Button) findViewById(R.id.jul_sensor_btn);
		mSens.setText("설정버튼 현재설정값:"+sufNum);
	
		mEllapse = (TextView) findViewById(R.id.jul_time_view);
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		mSm.unregisterListener(mSensorListenr);
		mTime.removeMessages(0);
	}
	Handler mTime = new Handler(){
		public void handleMessage(Message msg){
			mEllapse.setText(getEllapse());
			mTime.sendEmptyMessage(0);
		}
	};
	
	 String getEllapse(){
		long now = SystemClock.elapsedRealtime();
		long ell = now - mBaseTime;
		String sEll = String.format("%02d:%02d:%02d", ell/1000/60,(ell/1000)%60,(ell%1000)/10);
		return sEll;
	 }
	protected Dialog onCreateDialog(int id){
		
		if(id == 0){
			return new AlertDialog.Builder(JUL_Activity.this)
			.setTitle("stop!")
			.setMessage("줄넘기 개수 : "+sumCount+"\n"+"줄넘기 시간 : "+lastlap)
			.setPositiveButton("기록보기", new DialogInterface.OnClickListener() {
				
				@Override
				public void onClick(DialogInterface dialog, int which) {
					Intent intent= new Intent(JUL_Activity.this, RecordActivity.class);
					Record re = new Record();
					re.counter = String.valueOf(sumCount);
					re.time = lastlap;
					arRecord.add(re);
					
					intent.putParcelableArrayListExtra("Recoders", arRecord);
					startActivity(intent);
				}
			})
			.setNegativeButton("확인", new DialogInterface.OnClickListener() {
				
				@Override
				public void onClick(DialogInterface dialog, int which) {
					Record re = new Record();
					re.counter = String.valueOf(sumCount);
					re.time = lastlap;
					arRecord.add(re);
					Toast.makeText(JUL_Activity.this, "저장하였습니다", Toast.LENGTH_LONG).show();
				}
			})
			.create();
		}
		return null;
	}
		protected void onPrepareDialog(int id, Dialog dialog) {
			if(id == 0){
					removeDialog(0);
					}
			};
		
	
		
		
		SensorEventListener mSensorListenr = new SensorEventListener() {//센서
		
		@Override
		public void onAccuracyChanged(Sensor sensor, int accuracy) {}
		
		@Override
		public void onSensorChanged(SensorEvent event) {
			switch (event.sensor.getType()){
				 case Sensor.TYPE_ACCELEROMETER:
					 AccelValue av =new AccelValue();
					 av.value[0]= event.values[0];
					 av.value[1]= event.values[1];
					 av.value[2]= event.values[2];
					 av.time = event.timestamp/10000L;
					 
					 arValue.add(av);
					 
					 long now = System.currentTimeMillis();
					 if(now - mApplyTime<mSenGap){
						 break;
					 }
					 
					 float[]min = new float[]{100,100,100};
					 float[]max = new float[]{-100,-100,-100};
					 for(int i= arValue.size()-1;i>=0;i--){
						 AccelValue v = arValue.get(i);
						 for(int j = 0;j<3;j++){
							 min[j] = Math.min(min[j],v.value[j]);
							 max[j] = Math.max(max[j],v.value[j]);
						 }
						 
					 }
					 float[] diff = new float[3];
					 for(int j=0;j<3;j++){
						 diff[j] = Math.abs(max[j]-min[j]);
					}
			
					if(diff[0]>mSenRange&&(startFlag==true)){
						mApplyTime =now;
						mCounter++;
						sumCount=mCounter+sufNum;
						mCounterText.setText(""+sumCount);
						arValue.clear();
						
					}
			}
		}
	};//센서 리스터 끝
	public void mOnClick(View v){
		switch(v.getId()){
			
			case R.id.jul_clear_btn:
				mCounterText.setText("0");
				mCounter = 0;
				mTime.removeMessages(0);
				mEllapse.setText("00:00:00");
				Toast.makeText(JUL_Activity.this, "초기화", Toast.LENGTH_LONG).show();
				break;
			case R.id.jul_start_btn:
				if(startFlag==false){
				mStart.setText("Stop");
				mBaseTime= SystemClock.elapsedRealtime();
				mTime.sendEmptyMessage(0);
				//Toast.makeText(JUL_Activity.this, "Stop"+sufNum, Toast.LENGTH_LONG).show();
				startFlag=true;
				}else{
					mStart.setText("start");
					//Toast.makeText(JUL_Activity.this, "start"+sufNum, Toast.LENGTH_LONG).show();
					mTime.removeMessages(0);
					startFlag=false;
					lastlap = getEllapse();
					showDialog(0);
				}
				break;
			case R.id.jul_sensor_btn:
				startActivity(new Intent(this, SensorSetActivity.class));
				break;
			
		}
	}
	@Override
	protected void onResume() {
		super.onResume();
		mCounterText.setText("0");
		mCounter = 0;//초기화
	}
	@Override
	protected void onRestart() {
		super.onRestart();
		SharedPreferences pref = getSharedPreferences("JUL", 0);
		sufNum = pref.getInt("sufNum", 0);
		mSens.setText("설정버튼 현재설정값:"+sufNum);//뒤로 이동햇을시 설정
	}
}
